<?php
/**
 * This file is part of Task Agile.
 * Task Agile is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License.
 * Task Agile is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Task Agile.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category   TaskAgile
 * @package    Controller
 * @copyright  Copyright (c) 20010-2010 Estrada Virtual (http://estradavirtual.com.br)
 * @license    http://www.gnu.org/licenses/gpl.txt GPLv3
 * @version    $Id$
*/
/**
 * Model de User
 * @filesource  01/08/2010
 * @author      Cristiano Teles <cristianoteles@estradavirtual.com.br>
 * @copyright   Copyright <2010> Estrada Virtual
 * @package     Task
 * @subpackage  task.application.models
 * @version     $Id$
 */
class User extends Tev_Db_Table
{
    const ADMIN           = 'T';
    const ROLE_ADMIN      = 'admin';
    const ROLE_ENTERPRISE = 'enterprise';

    protected $_name             = 'user';
    protected $_dependentTables  = array('EnterpriseUser', 'Task', 'TaskComment');
    protected $_primary          = array('id');

    /**
     * Faz o login caso o email e senha estejam corretos
     * @param string $email
     * @param string $password
     * @return boolean
     */
    public function login($email, $password)
    {
        $this->logout();

        $db = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'user','email','password', 'md5(?)');

        $authAdapter->setIdentity($email)
                    ->setCredential($password);
        $result = $authAdapter->authenticate();
        if ($result->isValid()) {
            $oIdentify = $authAdapter->getResultRowObject(null, 'password');
            if (User::ADMIN == $oIdentify->admin) {
                $oIdentify->role = User::ROLE_ADMIN;
            } else {
                $oIdentify->role = User::ROLE_ENTERPRISE;
            }

            $auth = Zend_Auth::getInstance();
            $auth->getStorage()->write($oIdentify);

            // save log
            $login = new Login();
            $login->insert(array('dt_login' => date('Y-m-d H:i:s'), 'fk_user' => $oIdentify->id));
            return true;
        }
        return false;
    }

    /**
     * Faz o logout do usuario
     * @return boolean
     */
    public function logout()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
    }

}
